package com.h5ve.wxmp.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.h5ve.base.api.R;
import com.h5ve.base.constant.AppConstants;
import com.h5ve.wxmp.entity.WxUser;
import com.h5ve.wxmp.service.WxUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 微信用户
 *
 * @author www.joolun.com
 * @date 2019-03-25 15:39:39
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(AppConstants.APP_WXMP + "/wxUser")
public class WxUserController {

    private final WxUserService wxUserService;

    /**
     * 分页查询
     *
     * @param page   分页对象
     * @param wxUser 微信用户
     * @return
     */
    @GetMapping("/list")
    @SaCheckPermission("wxUser_view")
    public R getWxUserPage(Page page, WxUser wxUser, String tagId) {
        Wrapper<WxUser> queryWrapper;
        if (StringUtils.isNotBlank(tagId)) {
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .and(wrapper -> wrapper
                            .eq(WxUser::getTagidList, "[" + tagId + "]")
                            .or()
                            .like(WxUser::getTagidList, "," + tagId + ",")
                            .or()
                            .likeRight(WxUser::getTagidList, "[" + tagId + ",")
                            .or()
                            .likeLeft(WxUser::getTagidList, "," + tagId + "]"));
        } else if (StrUtil.isNotBlank(wxUser.getNickName())) {
            String nickName = wxUser.getNickName();
            wxUser.setNickName(null);
            queryWrapper = Wrappers.lambdaQuery(wxUser)
                    .like(WxUser::getNickName, nickName);
        } else {
            queryWrapper = Wrappers.lambdaQuery(wxUser);
        }
        IPage<WxUser> userPage = wxUserService.page(page, queryWrapper);
        return R.ok(userPage.getRecords(), userPage.getTotal());
    }


    /**
     * 通过id查询微信用户
     *
     * @param id id
     * @return R
     */
    @GetMapping("/{id}")
    @SaCheckPermission("wxUser_get")
    public R getById(@PathVariable("id") String id) {
        return R.ok(wxUserService.getById(id));
    }

    /**
     * 新增微信用户
     *
     * @param wxUser 微信用户
     * @return R
     */
    @PostMapping
    @SaCheckPermission("wxUser_add")
    public R save(@RequestBody WxUser wxUser) {
        return R.ok(wxUserService.save(wxUser));
    }

    /**
     * 修改微信用户
     *
     * @param wxUser 微信用户
     * @return R
     */
    @PutMapping
    @SaCheckPermission("wxUser_edit")
    public R updateById(@RequestBody WxUser wxUser) {
        return R.ok(wxUserService.updateById(wxUser));
    }

    /**
     * 通过id删除微信用户
     *
     * @param id id
     * @return R
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("wxUser_del")
    public R removeById(@PathVariable String id) {
        return R.ok(wxUserService.removeById(id));
    }

    @PostMapping("/sync")
    @SaCheckPermission("wxUser_sync")
    public R sync() {
        try {
            wxUserService.syncWxUser();
            return R.ok();
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("同步微信用户失败", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改微信用户备注
     *
     * @param wxUser
     * @return
     */
    @PutMapping("/remark")
    @SaCheckPermission("wxUser_edit")
    public R remark(@RequestBody WxUser wxUser) {
        try {
            return R.ok(wxUserService.updateRemark(wxUser));
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("修改微信用户备注失败", e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 打标签
     *
     * @param data
     * @return
     */
    @PutMapping("/taglist")
    @SaCheckPermission("wxUser_tags")
    public R tagidList(@RequestBody JSONObject data) {
        try {
            String appId = data.getStr("appId");
            String taggingType = data.getStr("taggingType");
            JSONArray tagIdsArray = data.getJSONArray("tagIds");
            JSONArray openIdsArray = data.getJSONArray("openIds");
            String[] openIds = openIdsArray.toArray(new String[0]);
            for (Object tagId : tagIdsArray) {
                wxUserService.tagging(taggingType, Long.valueOf(String.valueOf(tagId)), openIds);
            }
            return R.ok();
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.error("修改微信用户备注失败", e);
            return R.error(e.getMessage());
        }
    }

}
